package cn.bluarry.weathert;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import org.jetbrains.annotations.NotNull;
import org.litepal.LitePal;
import org.litepal.crud.LitePalSupport;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.bluarry.weathert.db.City;
import cn.bluarry.weathert.db.County;
import cn.bluarry.weathert.db.Province;
import cn.bluarry.weathert.util.HttpUtil;
import cn.bluarry.weathert.util.Utility;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ChooseAreaFragment extends Fragment {
    public static final int LEVEL_PROVINCE=0;
    public static final int LEVEL_CITY=1;
    public static final int LEVEL_CONTRY=2;

    private ProgressDialog progressDialog;
    private TextView titelText;
    private Button backButton;

    private ListView listView;
    private ArrayAdapter<String> adapter;
    private List<String> dataList=new ArrayList<>();

    private List<Province> provinceList;
    private List<City> cityList;
    private List<County> countyList;

    private Province selectedProvince;
    private City selectedCity;
    private int currentLevel;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.choose_area,container,false);
        titelText=v.findViewById(R.id.title_text);
        backButton=v.findViewById(R.id.back_button);
        listView=v.findViewById(R.id.list_view);
        adapter=new ArrayAdapter<>(getContext(),android.R.layout.simple_list_item_1,dataList);
        listView.setAdapter(adapter);
        return v;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(currentLevel==LEVEL_PROVINCE){
                    selectedProvince=provinceList.get(position);
                    queryCities();
                }else if(currentLevel==LEVEL_CITY){
                    selectedCity=cityList.get(position);
                    queryCountries();
                }else if(currentLevel==LEVEL_CONTRY){
                    String weatherId=countyList.get(position).getWeatherId();
                    if(getActivity() instanceof MainActivity){
                        Intent intent=new Intent(getActivity(),WeatherActivity.class);
                        intent.putExtra("weather_id",weatherId);
                        startActivity(intent);
                        getActivity().finish();
                    }else if(getActivity() instanceof WeatherActivity){
                        WeatherActivity wa=(WeatherActivity)getActivity();
                        wa.drawerLayout.closeDrawers();
                        wa.swipeRefresh.setRefreshing(true);
                        wa.requestWeather(weatherId);
                    }

                }
            }
        });

        backButton.setOnClickListener((v)->{
            if(currentLevel==LEVEL_CONTRY){
                queryCities();
            }else if(currentLevel==LEVEL_CITY){
                queryProvinces();
            }
        });
        queryProvinces();
    }

    /**
     * 查询所有的省，本地数据库没有就去请求接口
     */
    private void queryProvinces(){
        titelText.setText("中国");
        backButton.setVisibility(View.GONE);
        provinceList= LitePal.findAll(Province.class);
        if(provinceList.size()>0){
            dataList.clear();
            for(Province p:provinceList){
                dataList.add(p.getProvinceName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel=LEVEL_PROVINCE;
        }else{
            String addr="http://guolin.tech/api/china";
            queryFromServer(addr,"province");
        }
    }

    private void queryCities(){
        titelText.setText(selectedProvince.getProvinceName());
        backButton.setVisibility(View.VISIBLE);
        cityList=LitePal.where("provinceid = ?",String.valueOf(selectedProvince.getId())).find(City.class);
        if(cityList.size()>0){
            dataList.clear();
            for(City c:cityList){
                dataList.add(c.getCityName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel=LEVEL_CITY;
        }else{
            int provinceCode=selectedProvince.getProvinceCode();
            String addr="http://guolin.tech/api/china/"+provinceCode;
            queryFromServer(addr,"city");
        }
    }

    private void queryCountries(){
        titelText.setText(selectedCity.getCityName());
        backButton.setVisibility(View.VISIBLE);
        countyList=LitePal.where("cityid = ?",String.valueOf(selectedCity.getId())).find(County.class);
        if(countyList.size()>0){
            dataList.clear();
            for(County c:countyList){
                    dataList.add(c.getCoutyName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel=LEVEL_CONTRY;
        }else{
            int pc=selectedProvince.getProvinceCode();
            int cc=selectedCity.getCityCode();
            String  addr="http://guolin.tech/api/china/"+pc+"/"+cc;
            queryFromServer(addr,"county");
        }
    }



    /**
     * 根据传入的地址和类型从服务器上获取数据
     * @param addr
     * @param type
     */
    private  void queryFromServer(String addr,final String type){
        showProgressDialog();
        HttpUtil.sendOkHttpRequest(addr, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                getActivity().runOnUiThread(()->{
                    closeProgressDialog();
                    Toast.makeText(getContext(),"加载失败",Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String responseText=response.body().string();
                boolean result=false;
                if(type.equals("province")){
                    result= Utility.handleProvinceResponse(responseText);
                }else if(type.equals("city")){
                    result=Utility.handleCityResponse(responseText,selectedProvince.getId());
                }else if(type.equals("county")){
                    result=Utility.handleContryResponse(responseText,selectedCity.getId());
                }
                if(result){
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            closeProgressDialog();
                            if(type.equals("province")){
                                queryProvinces();
                            }else if(type.equals("city")){
                                queryCities();
                            }else if(type.equals("county")){
                                queryCountries();
                            }
                        }
                    });
                }
            }
        });



    }


    private void showProgressDialog(){
        if(progressDialog==null){
            progressDialog=new ProgressDialog(getActivity());
            progressDialog.setMessage("正在加载");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    private void closeProgressDialog(){
        if(progressDialog!=null){
            progressDialog.dismiss();
        }
    }

}
